package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;

/**
 * 该工具类，主要的功能实现对象与json串的互相转化
 * 1.对象转化为json
 * 2.json转化为对象
 */
public class ObjectMapperUtil {
    private static final ObjectMapper MAPPER=new ObjectMapper();

    //1.对象转化为json
    public static String toJSON(Object object){
        try {
            return MAPPER.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    //2.json转化为对象  要求用户传递什么类型就返回什么对象？？
    public static <T> T toObj(String json,Class<T> target){
        try {
            return MAPPER.readValue(json, target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }


}
